package com.source.linkedin;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class FormatJDOM {

    private Document doc;

    public FormatJDOM() throws ParserConfigurationException, SAXException, IOException {
        inicializacion();
    }

    public void inicializacion() throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(new InputSource(new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?><datos><datos_personales></datos_personales><educacions></educacions><certificaciones></certificaciones><idiomas></idiomas><positions></positions></datos>")));
        doc.getDocumentElement().normalize();

    }

    @SuppressWarnings("CallToThreadDumpStack")
    public String doProceso(String recibe_cadenaDatos) throws IOException {

        //LOG
        LogManager lm = LogManager.getLogManager();
        Logger logger;
        Date d1 = new Date();
        DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
        String fecha = df.format(d1);

        //FileHandler fh = new FileHandler(getBundle().getString("pathLog") + fecha + ".txt", true);
        //FileHandler fh = new FileHandler(getBundle().getString("pathLog") + "LogErrorres.txt", true);
        logger = Logger.getLogger("LoggingExample1");
        lm.addLogger(logger);
        logger.setLevel(Level.ALL);
        SimpleFormatter formatter = new SimpleFormatter();
        // fh.setFormatter(formatter);
        // logger.addHandler(fh);


        try {

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document docRoot = dBuilder.parse(new InputSource(new StringReader(recibe_cadenaDatos)));

            docRoot.getDocumentElement().normalize();

            NodeList nodeList = docRoot.getElementsByTagName("person");

            int tamaño = nodeList.getLength();

            String first_name_valor;
            String first_name_nombre;
            String last_name_valor;
            String last_name_nombre;
            String headline_valor;
            String headline_nombre;
            String industry_valor;
            String industry_nombre;
            String summary_valor;
            String summary_nombre;
            String foto_valor = "";
            String foto_nombre;

            Node nodo = nodeList.item(0);

            Element element = (Element) nodo;

            NodeList hijos = element.getElementsByTagName("first-name").item(0).getChildNodes();
            Node nodoHijo = (Node) hijos.item(0);
            first_name_valor = nodoHijo.getNodeValue();
            first_name_nombre = "first_name";

            hijos = element.getElementsByTagName("last-name").item(0).getChildNodes();
            nodoHijo = (Node) hijos.item(0);
            last_name_valor = nodoHijo.getNodeValue();
            last_name_nombre = "last_name";

            hijos = element.getElementsByTagName("headline").item(0).getChildNodes();
            nodoHijo = (Node) hijos.item(0);
            headline_valor = nodoHijo.getNodeValue();
            headline_nombre = "headline";

            hijos = element.getElementsByTagName("industry").item(0).getChildNodes();
            nodoHijo = (Node) hijos.item(0);
            industry_valor = nodoHijo.getNodeValue();
            industry_nombre = "industry";

            hijos = element.getElementsByTagName("summary").item(0).getChildNodes();
            nodoHijo = (Node) hijos.item(0);
            summary_valor = nodoHijo.getNodeValue();
            summary_nombre = "summary";

            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList nodeLista = (NodeList)xpath.evaluate("/person/picture-url", docRoot.getDocumentElement(), XPathConstants.NODESET);
            for (int i = 0; i < nodeLista.getLength(); i++) {
                foto_valor = nodeLista.item(i).getTextContent();
            }
            foto_nombre = "foto";

            Map mapa_datosPersonales = new HashMap();
            mapa_datosPersonales.put(first_name_nombre, first_name_valor);
            mapa_datosPersonales.put(last_name_nombre, last_name_valor);
            mapa_datosPersonales.put(headline_nombre, headline_valor);
            mapa_datosPersonales.put(industry_nombre, industry_valor);
            mapa_datosPersonales.put(summary_nombre, summary_valor);
            mapa_datosPersonales.put(foto_nombre, foto_valor);
            doFormateoDatosPersonales(mapa_datosPersonales);

            //Educacion
            String education_school_name_valor = "";
            String education_degree_valor = "";
            String education_start_date_year_valor = "";
            String education_study_valor = "";
            //String education_start_date_month_valor="";
            String education_end_date_year_valor = "";

            hijos = element.getElementsByTagName("educations").item(0).getChildNodes();
            Map<String, String> mapa_educacion = new HashMap();

            for (int s = 0; s < hijos.getLength(); s++) {
                Node firstEducationNode = hijos.item(s);
                if (firstEducationNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element firstEducationElement = (Element) firstEducationNode;
                    //school-name: centro
                    NodeList schoolNameList = firstEducationElement.getElementsByTagName("school-name");
                    if (schoolNameList != null) {
                        schoolNameList = firstEducationElement.getElementsByTagName("school-name").item(0).getChildNodes();
                        nodoHijo = (Node) schoolNameList.item(0);
                        education_school_name_valor = nodoHijo.getNodeValue();
                    }

                    //degree : titulo
                    NodeList degreeList = firstEducationElement.getElementsByTagName("degree");
                    if (degreeList.item(0) != null) {
                        degreeList = firstEducationElement.getElementsByTagName("degree").item(0).getChildNodes();
                        nodoHijo = (Node) degreeList.item(0);
                        education_degree_valor = nodoHijo.getNodeValue();
                    }

                    //field-of-stuyd : estudio
                    NodeList studyList = firstEducationElement.getElementsByTagName("field-of-study");
                    if (studyList.item(0) != null) {
                        studyList = firstEducationElement.getElementsByTagName("field-of-study").item(0).getChildNodes();
                        nodoHijo = (Node) studyList.item(0);
                        education_study_valor = nodoHijo.getNodeValue();
                    }


                    //start-date :periodo
                    NodeList start_dateList = firstEducationElement.getElementsByTagName("start-date");
                    Element element_start_date = (Element) start_dateList.item(0);

                    if (element_start_date != null) {
                        NodeList start_dateList2 = element_start_date.getElementsByTagName("year");
                        //    NodeList start_dateList3 = element_start_date.getElementsByTagName("month");

                        if (start_dateList2.item(0) != null) {
                            start_dateList2 = element_start_date.getElementsByTagName("year").item(0).getChildNodes();
                            nodoHijo = (Node) start_dateList2.item(0);
                            education_start_date_year_valor = nodoHijo.getNodeValue();
                        }

                    }

                    //end-date :periodo
                    NodeList end_dateList = firstEducationElement.getElementsByTagName("end-date");
                    Element element_end_date = (Element) end_dateList.item(0);

                    if (element_end_date != null) {
                        NodeList end_dateList2 = element_end_date.getElementsByTagName("year");
                        // NodeList end_dateList3 = element_end_date.getElementsByTagName("month");

                        if (end_dateList2.item(0) != null) {
                            end_dateList2 = element_end_date.getElementsByTagName("year").item(0).getChildNodes();
                            nodoHijo = (Node) end_dateList2.item(0);
                            education_end_date_year_valor = nodoHijo.getNodeValue();
                        }

                    }

                    mapa_educacion.put("intsuni", education_school_name_valor);
                    mapa_educacion.put("titulo", education_degree_valor);
                    mapa_educacion.put("estudio", education_study_valor);
                    mapa_educacion.put("etapa", education_start_date_year_valor + " - " + education_end_date_year_valor);
                    doFormateoEducacion(mapa_educacion);
                }

            }

            //Certificacion
            String certificacion_name_valor = "";
            if (element.getElementsByTagName("certifications").item(0) != null) {
                hijos = element.getElementsByTagName("certifications").item(0).getChildNodes();
                Map<String, String> mapa_certificacion = new HashMap();

                for (int s = 0; s < hijos.getLength(); s++) {
                    Node firstCertificacionNode = hijos.item(s);
                    if (firstCertificacionNode.getNodeType() == Node.ELEMENT_NODE) {

                        Element firstCertificacionElement = (Element) firstCertificacionNode;
                        NodeList schoolNameList = firstCertificacionElement.getElementsByTagName("name");
                        if (schoolNameList != null) {
                            certificacion_name_valor = schoolNameList.item(0).getTextContent();
                        }
                        mapa_certificacion.put("nombre", certificacion_name_valor);
                        doFormateoCertificacion(mapa_certificacion);
                    }

                }
            }

            //**************************** inicio *****************//

            //Idiomas
            String idioma_name_valor = "";
            if (element.getElementsByTagName("languages").item(0) != null) {
                hijos = element.getElementsByTagName("languages").item(0).getChildNodes();
                Map<String, String> mapa_idioma = new HashMap();

                for (int s = 0; s < hijos.getLength(); s++) {
                    Node firstIdiomaNode = hijos.item(s);
                    if (firstIdiomaNode.getNodeType() == Node.ELEMENT_NODE) {

                        Element firstIdiomaElement = (Element) firstIdiomaNode;
                        NodeList schoolNameList = firstIdiomaElement.getElementsByTagName("name");
                        if (schoolNameList != null) {
                            idioma_name_valor = schoolNameList.item(0).getTextContent();
                        }

                        mapa_idioma.put("nombre", idioma_name_valor);

                        doFormateoIdioma(mapa_idioma);
                    }

                }
            }
            //************************ final **********************//

            //Idiomas
            String position_title_valor = "";
            String position_summary_valor = "";
            String position_start_date_year_valor = "";
            String position_start_date_month_valor = "";
            String position_end_date_year_valor = "";
            String position_end_date_month_valor = "";
            String positionCompanyName_valor = "";

            NodeList hijos_position = element.getElementsByTagName("positions").item(0).getChildNodes();
            Map mapa_position = new HashMap();

            for (int s = 0; s < hijos_position.getLength(); s++) {
                Node firstPositionNode = hijos_position.item(s);
                if (firstPositionNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element firstPositionElement = (Element) firstPositionNode;

                    NodeList titleList = firstPositionElement.getElementsByTagName("title");
                    if (titleList != null) {
                        titleList = firstPositionElement.getElementsByTagName("title").item(0).getChildNodes();
                        nodoHijo = (Node) titleList.item(0);
                        position_title_valor = nodoHijo.getNodeValue();

                    }

                    NodeList summaryList = firstPositionElement.getElementsByTagName("summary");
                    if (summaryList.item(0) != null) {
                        summaryList = firstPositionElement.getElementsByTagName("summary").item(0).getChildNodes();
                        nodoHijo = (Node) summaryList.item(0);
                        position_summary_valor = nodoHijo.getNodeValue();
                    }

                    //start-date
                    NodeList start_dateList = firstPositionElement.getElementsByTagName("start-date");
                    Element element_start_date = (Element) start_dateList.item(0);

                    if (element_start_date != null) {
                        NodeList start_dateList2 = element_start_date.getElementsByTagName("year");
                        NodeList start_dateList3 = element_start_date.getElementsByTagName("month");

                        if (start_dateList2.item(0) != null) {
                            start_dateList2 = element_start_date.getElementsByTagName("year").item(0).getChildNodes();
                            nodoHijo = (Node) start_dateList2.item(0);
                            position_start_date_year_valor = nodoHijo.getNodeValue();
                        }

                        if (start_dateList3.item(0) != null) {
                            start_dateList3 = element_start_date.getElementsByTagName("month").item(0).getChildNodes();
                            nodoHijo = (Node) start_dateList3.item(0);
                            position_start_date_month_valor = nodoHijo.getNodeValue();
                        }
                    }

                    //end-date
                    NodeList end_dateList = firstPositionElement.getElementsByTagName("end-date");
                    Element element_end_date = (Element) end_dateList.item(0);

                    if (element_end_date != null) {
                        NodeList end_dateList2 = element_end_date.getElementsByTagName("year");
                        NodeList end_dateList3 = element_end_date.getElementsByTagName("month");

                        if (end_dateList2.item(0) != null) {
                            end_dateList2 = element_end_date.getElementsByTagName("year").item(0).getChildNodes();
                            nodoHijo = (Node) end_dateList2.item(0);
                            position_end_date_year_valor = nodoHijo.getNodeValue();
                        }

                        if (end_dateList3.item(0) != null) {

                            end_dateList3 = element_end_date.getElementsByTagName("month").item(0).getChildNodes();
                            nodoHijo = (Node) end_dateList3.item(0);
                            position_end_date_month_valor = nodoHijo.getNodeValue();
                        }
                    }

                    //company
                    NodeList companyList = firstPositionElement.getElementsByTagName("company");
                    Element element_company = (Element) companyList.item(0);

                    NodeList companyListName = element_company.getElementsByTagName("name");

                    if (companyListName.item(0) != null) {

                        companyListName = element_company.getElementsByTagName("name").item(0).getChildNodes();
                        nodoHijo = (Node) companyListName.item(0);
                        positionCompanyName_valor = nodoHijo.getNodeValue();

                    }

                    mapa_position.put("funciones", position_summary_valor);
                    mapa_position.put("periodo", position_start_date_month_valor + "/" + position_start_date_year_valor + " - " + position_end_date_month_valor + "/" + position_end_date_year_valor);
                    mapa_position.put("empresa", positionCompanyName_valor);
                    mapa_position.put("cargo", position_title_valor);
                    doFormateoPositions(mapa_position);
                }

            }



            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            DOMSource source = new DOMSource(doc);
            //PrintWriter writer = new PrintWriter(System.out);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);
            return writer.toString();
        } catch (Throwable ex) {
            logger.log(Level.FINEST, "Error --> " + ex.getMessage(), ex);
        }

        //      fh.close();
        return null;
    }

    public void doFormateoDatosPersonales(Map mapa2) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException {

        NodeList lista_datos_personales = doc.getElementsByTagName("datos_personales");
        Node nodo_datos_personales = lista_datos_personales.item(0);

        Iterator it = mapa2.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry e = (Map.Entry) it.next();
            Element elemento2 = doc.createElement("variables");
            elemento2.setAttribute("name", e.getKey().toString());
            elemento2.setAttribute("valor", e.getValue().toString());
            nodo_datos_personales.appendChild(elemento2);
        }

    }

    public void doFormateoEducacion(Map mapa2) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException {

        NodeList lista_educacions = doc.getElementsByTagName("educacions");
        Node nodo_educacions = lista_educacions.item(0);
        Element elemento1 = doc.createElement("educacion");

        Iterator it = mapa2.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry e = (Map.Entry) it.next();

            if (e.getKey() != "") {
                Element elemento2 = doc.createElement("variables");

                elemento2.setAttribute("name", e.getKey().toString());
                elemento2.setAttribute("valor", e.getValue().toString());

                elemento1.appendChild(elemento2);
            }
        }
        nodo_educacions.appendChild(elemento1);

    }

    public void doFormateoCertificacion(Map mapa2) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException {

        NodeList lista_certificacions = doc.getElementsByTagName("certificaciones");
        Node nodo_certificaciones = lista_certificacions.item(0);
        Element elemento1 = doc.createElement("certificacion");

        Iterator it = mapa2.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry e = (Map.Entry) it.next();

            if (e.getKey() != "") {
                Element elemento2 = doc.createElement("variables");

                elemento2.setAttribute("name", e.getKey().toString());
                elemento2.setAttribute("valor", e.getValue().toString());

                elemento1.appendChild(elemento2);
            }
        }
        nodo_certificaciones.appendChild(elemento1);

    }

    public void doFormateoIdioma(Map mapa2) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException {

        NodeList lista_idiomas = doc.getElementsByTagName("idiomas");
        Node nodo_idiomas = lista_idiomas.item(0);
        Element elemento1 = doc.createElement("idioma");

        Iterator it = mapa2.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry e = (Map.Entry) it.next();

            if (e.getKey() != "") {
                Element elemento2 = doc.createElement("variables");

                elemento2.setAttribute("name", e.getKey().toString());
                elemento2.setAttribute("valor", e.getValue().toString());

                elemento1.appendChild(elemento2);
            }
        }
        nodo_idiomas.appendChild(elemento1);

    }

    public void doFormateoPositions(Map mapa2) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException {

        NodeList lista_positions = doc.getElementsByTagName("positions");
        Node nodo_positions = lista_positions.item(0);
        Element elemento1 = doc.createElement("position");

        Iterator it = mapa2.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry e = (Map.Entry) it.next();

            if (e.getKey() != "") {
                Element elemento2 = doc.createElement("variables");

                elemento2.setAttribute("name", e.getKey().toString());
                elemento2.setAttribute("valor", e.getValue().toString());

                elemento1.appendChild(elemento2);
            }
        }
        nodo_positions.appendChild(elemento1);

    }
}
